package com.idealcn.define.view.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

import com.idealcn.define.view.R;
import com.idealcn.define.view.utils.DensityUtil;

import java.text.DecimalFormat;

import static android.util.TypedValue.COMPLEX_UNIT_SP;

/**
 * Created by ideal-gn on 2017/8/22.
 *
 * 1: 对于View来说,计算宽高是不考虑在布局中设置的margin值的,只考虑布局中设置的padding
 * 2：onMeasure时获取不到自身的宽高，onLayout可以通过getMeasuredWidth和getMeasuredHeight获取宽高，但不能通过getWidth和getHeight。
 *  onDraw时可以通过getWidth和getHeight获取宽高，也可以通过getMeasuredWidth和getMeasuredHeight获取宽高。
 */

public class ColorfulCircle extends View {

    private  RectF rectF = new RectF();

    private int progressType;
    public static final int CIRCLE = 0;
    public static final int LINE = 1;

    private float progress = 0.01f;


    private  ObjectAnimator animator;

    private int strokeWidth ;
    private Paint mTextPaint;
    private Paint mCirclePaint;
    //去掉小数点后数据
    private DecimalFormat decimalFormat = new DecimalFormat("0");
    //精确到小数点后两位
//    decimalFormat = new DecimalFormat(".00");

    private Paint.FontMetrics fontMetrics;

    public ColorfulCircle(Context context) {
        this(context,null);
    }

    public ColorfulCircle(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ColorfulCircle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ColorfulCircle);

        progressType = typedArray.getInt(R.styleable.ColorfulCircle_progress_type, CIRCLE);
        typedArray.recycle();


        //适配画笔宽度
        strokeWidth  = DensityUtil.dip2px(getContext(),5);

        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setStrokeWidth(strokeWidth);
        mCirclePaint.setStrokeJoin(Paint.Join.ROUND);
        mCirclePaint.setStyle(Paint.Style.STROKE);
        mCirclePaint.setStrokeCap(Paint.Cap.ROUND);
        mCirclePaint.setColor(getResources().getColor(R.color.colorAccent));

        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setColor(getResources().getColor(R.color.colorAccent));
        mTextPaint.setStrokeWidth(strokeWidth);
        mTextPaint.setStyle(Paint.Style.FILL);
        //适配字体
        float textSize = DensityUtil.applyDimension(COMPLEX_UNIT_SP, 20f, getResources().getDisplayMetrics());
        mTextPaint.setTextSize(textSize+0.5f);


        fontMetrics = mTextPaint.getFontMetrics();
    }

    /**
     * 自定义的属性,供ObjectAnimator调用
     * @param progress
     */
    public void setProgress(float progress) {
        this.progress = progress;
        invalidate();
    }

    public float getProgress() {
        return progress;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width  = getWidth();
        int height = getHeight();
        String text = decimalFormat.format(100*progress)+"%";




        switch (progressType){
            case CIRCLE:
                mCirclePaint.setStyle(Paint.Style.STROKE);
                mCirclePaint.setStrokeCap(Paint.Cap.ROUND);
                //设置矩形区域,去掉了画笔☆宽度的一半☆,避免画出来的圆形与边界相切
                rectF.set(strokeWidth/2,
                        strokeWidth/2,
                        getWidth()- strokeWidth/2,
                        getHeight() - strokeWidth/2
                ) ;
                canvas.drawText(text,
                        width/2  - mTextPaint.measureText(text)/2,
                        //设置字体在y轴的位置
                        height/2  - (fontMetrics.descent - fontMetrics.ascent)/2 - fontMetrics.ascent,
                        mTextPaint);
                canvas.drawArc(rectF, 0,  (360*progress + 0.5f),false,mCirclePaint);
                break;
            case LINE:
                canvas.drawText(text,
                        (width - mTextPaint.measureText(text))*progress,
                        //加一个画笔高度,避免字体和线条交叉
                        height/2  - (fontMetrics.descent - fontMetrics.ascent)/2 - fontMetrics.ascent - 3* strokeWidth,
                        mTextPaint);
                canvas.drawLine(0,
                         getHeight()/2,
                        getWidth()*progress,
                        getHeight()/2,
                        mCirclePaint);
                break;
                default:
                    break;
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width,height;

//        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
//        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
//        if (widthMode==MeasureSpec.EXACTLY){
//            width = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() ;
//        }else {
//            width = widthSize - getPaddingRight() - getPaddingLeft();
//        }
//
//
//        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
//        if (heightMode==MeasureSpec.EXACTLY){
//            height = getMeasuredHeight() ;
//        }else {
//            height = heightSize - getPaddingTop() - getPaddingBottom();
//        }

        /*
        不管是不是MeasureSpec.EXACTLY,getMeasureWidth和MeasureSpec.getSize(widthMeasureSpec);得到的值是
        一致的.
         */
        width = getMeasuredWidth() - getPaddingRight() - getPaddingLeft();
        height = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();

        //取最小值
        width = height = Math.min(width,height);


        setMeasuredDimension(width,height);
    }

    /**
     * 看官方文档
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    /**
     * 看官方文档注释
     */
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        animator = ObjectAnimator.ofFloat(this, "progress", 0,0.3f,0.5f,0.75f,1.0f);
        animator.setDuration(10000);
        animator.start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
//                requestLayout();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                Toast.makeText(getContext(), "end", Toast.LENGTH_SHORT).show();
                //动画结束后,释放动画
                animator = null;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                animator = null;
            }

        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //页面销毁时,释放动画
        if (animator!=null) {
            //动画中止,移除所有动画监听
            animator.removeAllListeners();
            animator.cancel();
            animator = null;
        }
    }


    public void setProgressType(int type) {
        this.progressType = type;
//        invalidate();//这里不需要调用这个方法
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "progress", 0.01f,0.3f,0.5f,0.75f,1.0f);
        animator.setDuration(10000);
        animator.start();
    }
}
